<?php

namespace App\Http\Requests\Backend;

use App\Models\Role;
use App\Http\Requests\BaseRequest;

class AdminRequest extends BaseRequest {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(\Request $request)
    {
        switch ($this->method()) {
            case 'POST':
                $rules = [
                    'name' => 'required|unique:users,name|max:255',
                    'email' => 'required|email|max:255',
                    'roleId' => 'required|exists:roles,id',
                    'password' => 'required|between:8,18|regex:/^\w+$/'
                ];
                break;
            case 'PUT':
            case 'PATCH':
                $rules = [
                    'name' => "required|unique:users,name,{$this->segment(3)}|max:255",
                    'email' => 'required|email|max:255',
                    'roleId' => 'required|exists:roles,id',
                    'password' => 'sometimes|between:8,18|regex:/^\w+$/'
                ];
                break;
            default:
                $rules = [];
                break;
        }

        return $rules;
    }

    public function messages()
    {
        return [
            'name.required' => '名称不能为空',
            'name.unique' => '名称已存在',
            'name.max' => '名称不能超过 :max 个字',
            'email.required' => '账号不能为空',
            'email.email' => ' 账号必须是邮箱格式',
            'email.max' => '账号不能超过 :max 个字',
            'roleId.required' => '请选择角色',
            'roleId.exists' => '角色不存在',
            'password.required' => '密码是必填项',
            'password.between' => '密码应该在 :min 到 :max 个字',
            'password.regex' => '密码只能是数字字母组合'
        ];
    }
}
